package com.org.gundutubruk;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;

public class GameActivity extends Activity {

	private static final String TAG = GameActivity.class.getSimpleName();
	private GameView gameView;
	BroadcastReceiver mReceiver;
	DisplayMetrics metrics;
	boolean isMultiplayer;
	
	public static final String EXTRA_WINNER_NAME = "WINNER_NAME";
	public static final String EXTRA_WINNER_GUNDU = "WINNER_GUNDU";	
	public static final String EXTRA_LOSERS_NAMES = "LOSERS_NAMES";
	public static final String EXTRA_LOSERS_GUNDU = "LOSERS_GUNDU";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);		
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);		
		//baru pertama kali dilaunch(sebelom nya belom dilaunch)
		Log.d(TAG,"start game activity");
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		//instansiasi gameView
		gameView = new GameView(this,metrics.widthPixels,metrics.heightPixels);
		setContentView(gameView);	
		//nangkep screen off atau on
		IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		mReceiver = new ScreenReceiver();
		registerReceiver(mReceiver, filter);
		//cek apakah GameActivity ini dijalankan dengan mode multiplayer
		Bundle b = getIntent().getExtras();
		if(b!=null) {
			isMultiplayer = b.getBoolean("isMultiplayer", false);
		}
	}
	
	@Override
	public boolean onKeyDown(int KeyCode, KeyEvent event) {				
		if(KeyCode == KeyEvent.KEYCODE_MENU || KeyCode == KeyEvent.KEYCODE_BACK) {
	    	Log.d(TAG,"tombol menu ditekan");
	    	if(gameView.state == GameView.PAUSE) {
	    		gameView.state = GameView.RUNNING;
	    		if(!gameView.thread.isAlive()) {//jika game loop sudah gak hidup
		    		gameView.initThread();
		    	}
	    	}else{
	    		gameView.state = GameView.PAUSE;	    			    	
	    	}
	    	return true;
	    }
	    return super.onKeyDown(KeyCode, event);	
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		overridePendingTransition(R.anim.fade, R.anim.hold);
	}
	
	@Override
	protected void onResume() {
		Log.d(TAG,"onResume()");
		/*
		 * ketika screen berubah dari mati ingin ke hidup
		 */
		if(!ScreenReceiver.wasScreenOn) {//ada perubahan kondisi layar
			gameView.state = GameView.PAUSE;
			gameView.initThread();
		}
		super.onResume();
		//activity-nya telah visible		
	}	
	
	@Override
	protected void onPause() {
		Log.d(TAG,"onPause()");
		/*
		 * ketika screen mati
		 */			
		gameView.state = GameView.PAUSE;
		gameView.thread.setRunning(false);//matiin thread
		//activity lain mengambil fokus			
		super.onPause();			
	}
	
	public void exitToGameMode() {		
		this.startActivity(new Intent("android.intent.action.GAMEMODE"));
		overridePendingTransition(R.anim.fade, R.anim.hold);				
		gameView.thread.setRunning(false);
		GameSound.changeMusicFromGameToMain(this);
		this.finish();		
	}
	
	public void onStop() {		
		unregisterReceiver(mReceiver);	
		super.onStop();
	}
	
	public void showTutorial(final String... texts) {
		final Context context = this;	
		if(GameSettingHolder.statusTutorial) {//jika tutorial di enable
			if(texts.length==1) {//jika panjangnya 1
				gameView.post(new Runnable() {
					@Override
					public void run() {
						AlertDialog.Builder builder = new AlertDialog.Builder(context);
						builder.setMessage(texts[0])
							   .setCancelable(false)
							   .setPositiveButton("Lanjut", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface arg0, int arg1) {								
										arg0.cancel();
									}							
							   	});
						builder.show();//tunjukkan kotak dialog
					}
				});	
			}
			else if(texts.length>=2) {//jika ada dua atau lebih parameter
				final AlertDialog[] arrDialog = new AlertDialog[texts.length];
				int[] arrint = new int[texts.length];
				for(int i=0;i<texts.length;i++) {
					arrint[i] = i;
				}
				/*
				 * loop mulai dari parameter terakhir, parameter terakhir kalo dipencet lanjut menghilangkan dirinya sendiri
				 * kalo bukan parameter terakhir dipencet lanjut akan lanjut ke alertdialog berikutnya
				 */
				for(final int i : arrint) {
					final AlertDialog.Builder builder = new AlertDialog.Builder(context);
					builder.setMessage(texts[texts.length-i-1]).setCancelable(false);				
					if(i!=0) {//jika bukan parameter terakhir
						builder.setPositiveButton("Lanjut", new DialogInterface.OnClickListener() {						
							@Override
							public void onClick(DialogInterface arg0, int arg1) {														
								gameView.post(new Runnable() {
									@Override
									public void run() {									
										arrDialog[texts.length-i].show();		
										if (texts[texts.length-i-1].equals(GameView.H_GARISBAWAH)){
							    			gameView.highlightGame(GameView.GARIS_BATAS_BAWAH);
										}
										if (texts[texts.length-i-1].equals(GameView.H_GARISAPOLLO)){
							    			gameView.highlightGame(GameView.GARIS_ROKET_APOLLO);
										}
										if (texts[texts.length-i-1].equals(GameView.H_GARISBULETAN)){
							    			gameView.highlightGame(GameView.GARIS_BULETAN);
										}

									}								
								});																
							}
						});	
						gameView.post(new Runnable() {
							@Override
							public void run() {
								arrDialog[texts.length-i-1] = builder.create();
							}						
						});									
					}else{//jika parameter terakhir
						builder.setPositiveButton("Lanjut", new DialogInterface.OnClickListener() {						
							@Override
							public void onClick(DialogInterface arg0, int arg1) {							
								arg0.cancel();
								if (texts[texts.length-i-1].equals(GameView.H_GARISBAWAH)){
					    			gameView.highlightGame(GameView.GARIS_BATAS_BAWAH);
								}
								if (texts[texts.length-i-1].equals(GameView.H_GARISAPOLLO)){
					    			gameView.highlightGame(GameView.GARIS_ROKET_APOLLO);
								}
								if (texts[texts.length-i-1].equals(GameView.H_GARISBULETAN)){
					    			gameView.highlightGame(GameView.GARIS_BULETAN);
								}
							}
						});	
						gameView.post(new Runnable() {						
							@Override
							public void run() {
								arrDialog[texts.length-i-1] = builder.create();
							}
						});									
					}
				}
				//tampilkan dialog yang pertama kali
				gameView.post(new Runnable() {				
					@Override
					public void run() {
						arrDialog[0].show();
					}
				});			
			}
		}
	}
	
	public void Win(){				
		if(isMultiplayer) {
			winMultiplayer();//mekanisme win buat multiplayer agak beda
			return;
		}
		//pass ke winneractivity siapa yang menang dan berapa jumlah kelereng yang didapat		
		Bundle b = new Bundle();	
		Intent intent = new Intent(GameActivity.this,WInnerActivity.class);		
		b.putString("namamenang", gameView.PlayerWinner());		
		b.putInt("avatarid", Utility.playerHolder.getPlayerWithName(gameView.PlayerWinner()).avatar);
		b.putInt("gundumenang", gameView.GunduPemenang());
		intent.putExtras(b);
		//update data pemenang		
		if(GameSettingHolder.modegame == GameSettingHolder.APOLLO || GameSettingHolder.modegame == GameSettingHolder.BULETAN) {			
			Utility.playerHolder.updatePlayerData(this,gameView.PlayerWinner(), gameView.GunduPemenang(), GameSettingHolder.taruhan, true);			
		}else if(GameSettingHolder.modegame==GameSettingHolder.DUEL) {
			//workaround buat duel(baca petunjuk updateplayerdata)			
			Utility.playerHolder.updatePlayerData(this,gameView.PlayerWinner(), gameView.GunduPemenang() + 1, GameSettingHolder.taruhan, true);		
		}
			
		//pass ke listrekap nama2 yang kalah dan jumlah gundu yang didapat
		String[] arrNamaPlayer = gameView.LoserPlayer();
		Player[] arrPlayer = new Player[gameView.LoserPlayer().length];		
		ListRekap.jumGundu = gameView.LoserGundu();
		for(int i=0;i<gameView.LoserPlayer().length;i++) {
			arrPlayer[i] = Utility.playerHolder.getPlayerWithName(arrNamaPlayer[i]);
			//update data yang kalah(jika bukan dalam mode multiplayer)	
			Utility.playerHolder.updatePlayerData(this,arrNamaPlayer[i],ListRekap.jumGundu[i],GameSettingHolder.taruhan,false);
		}		
		ListRekap.paraPemain = arrPlayer;
		startActivity(intent);		
		overridePendingTransition(R.anim.fade, R.anim.hold);
		gameView.thread.setRunning(false);
		GameSound.changeMusicFromGameToMain(this);//ganti musik jadi musik main menu		
		this.finish();
	}
	
	public void winMultiplayer() {
		Intent data = new Intent();
		//data player pemenang
		data.putExtra(EXTRA_WINNER_NAME,gameView.PlayerWinner());
		data.putExtra(EXTRA_WINNER_GUNDU, gameView.GunduPemenang());		
		//data player yang kalah
		data.putExtra(EXTRA_LOSERS_NAMES, gameView.LoserPlayer());
		data.putExtra(EXTRA_LOSERS_GUNDU,gameView.LoserGundu());
		this.setResult(Activity.RESULT_OK, data);
		
		gameView.thread.setRunning(false);
		GameSound.changeMusicFromGameToMain(this);//ganti musik jadi musik main menu
		this.finish();
	}
}
